package a1_4;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单类，关联客户、订单详情和支付方式
 */
public class Order {
    private LocalDateTime createDate; // 创建日期
    private OrderStatus status;       // 订单状态
    private Customer customer;        // 关联客户（多对一）
    private List<OrderDetail> orderDetails = new ArrayList<>(); // 关联订单详情（一对多）
    private Payment payment;          // 关联支付方式（一对一）

    public Order() {
        this.createDate = LocalDateTime.now(); // 默认创建日期为当前时间
        this.status = OrderStatus.CREATE;      // 默认状态为已创建
    }

    public Order(Customer customer) {
        this();
        this.customer = customer;
    }

    // 添加订单详情（一对多关联）
    public void addOrderDetail(OrderDetail detail) {
        orderDetails.add(detail);
        detail.setOrder(this); // 双向关联，同步详情的订单
    }

    // 计算订单总金额（所有详情小计之和）
    public double calculateTotalAmount() {
        return orderDetails.stream().mapToDouble(OrderDetail::calculateSubTotal).sum();
    }

    // 计算订单总重量（所有详情重量之和）
    public double calculateTotalWeight() {
        return orderDetails.stream().mapToDouble(OrderDetail::calculateWeight).sum();
    }

    // 关联支付方式（一对一）
    public void setPayment(Payment payment) {
        this.payment = payment;
        // 支付成功后更新订单状态为已支付
        if (payment.validatePayment()) {
            this.status = OrderStatus.PAID;
        }
    }

    // Getter/Setter
    public LocalDateTime getCreateDate() {
        return createDate;
    }

    public void setCreateDate(LocalDateTime createDate) {
        this.createDate = createDate;
    }

    public OrderStatus getStatus() {
        return status;
    }

    public void setStatus(OrderStatus status) {
        this.status = status;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public List<OrderDetail> getOrderDetails() {
        return new ArrayList<>(orderDetails);
    }

    public Payment getPayment() {
        return payment;
    }
}
